package com.ocean.admin.extension.security.service;

import com.ocean.admin.extension.security.PermissionServiceExtend;
import com.ocean.admin.extension.security.core.SysUserDetails;
import com.ocean.admin.service.ISysMenuService;
import com.ocean.admin.service.ISysRoleService;
import com.ocean.admin.service.ISysUserService;
import com.ocean.core.util.constants.ConstantsAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 用户验证处理
 *
 * @author zhang
 * @since 2022-8-16
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysMenuService iSysMenuService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private PermissionServiceExtend permissionServiceExtend;

    /**
     * 授权
     *
     * @param username username
     * @return 用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUserDetails userDetails = iSysUserService.selectUserByUsername(username);
        if (userDetails != null) {
            this.buildUser(userDetails);
            return userDetails;
        }
        throw new UsernameNotFoundException(ConstantsAttribute.PASSWORD_ERROR);
    }

    private void buildUser(SysUserDetails user) {
        Set<String> roles = iSysRoleService.selectRolesByUserId(user.getUserId());
        Set<String> permission = iSysMenuService.selectMenuPermsByUserId(user.getUserId());
        if (permissionServiceExtend.hasAdminRoleKey(roles)) {
            permission.add("*:*:*");
        }
        user.setPermissions(permission);
        user.setRoles(roles);
    }
}
